<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
       
</head>

<body>
    <div id="div">
        总票数:{{totalVote}}票
        <!-- v-bind：接收整个对象,在子组件会以解构后的参数形式接收 -->
        <!-- v-model:1.表单元素内  2.自定义组件 -->
        <first-com v-for="person in personList" 
        v-bind="person"
        :total="totalVote"
        @voting="person.vote=$event"
        ></first-com>
    </div>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.4/axios.min.js"></script>

    <script>
        //app本生也是组件，根(root)组件
        const app = Vue.createApp({
            data() {
                return {
                    personList: [
                        { name: '张三', vote: 0, sex:'m', age:'10' },
                        { name: '李四', vote: 0, sex:'m', age:'10' },
                        { name: '王五', vote: 0, sex:'m', age:'10' },
                        { name: '老六', vote: 0, sex:'m', age:'10' },
                    ]
                }
            },
            computed: {
                totalVote() {
                    /* let sum = 0;
                    this.personList.forEach(element => {
                        sum+=element.vote;
                    });
                    return sum; */

                    //sum=0
                    //1.sum=sum+cur.vote
                    //2.su
                    return this.personList.reduce((sum, cur) => ((sum += cur.vote), sum), 0);
                }
            }

        });

        app.component('FirstCom', {
            template: `
                <div class="first-com">
                    {{name}} - {{vote}}<br/>
                    <div>{{Percent}}</div>
                    <button @click="onCha">点击</button>
                </div>
            `,
            props:['name','vote','total'],
            //禁止属性透传
            inheritAttrs:false,
            methods: {
                onCha(){
                    console.log(this.$attrs);
                    this.$emit('voting',this.vote+1);
                }
            },
            computed:{
                Percent(){
                    if(this.total === 0) return '0%';
                    return (this.vote/this.total*100).toFixed(2)+'%';
                }
            }
        });

        app.mount('#div')

    </script>

</body>

</html>